﻿using Quartz;
using YunQue.Core.Common.Enums;
using YunQue.Core.Common.Helpers;

namespace YunQue.Core.Common.QuartzManager
{
    /// <summary>
    /// 通用的调度任务执行类
    /// </summary>
    public class SchedulerJob : IJob
    {
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            var jobName = context.JobDetail.Key.Name;
            Console.WriteLine($"任务 {jobName} 开始执行，时间：{DateTime.Now}");
            var jobDataMap = context.JobDetail.JobDataMap;
            var paramJson = jobDataMap.GetString(ConfigManager.JOB_DATA_KEY);
            JobExecuteParam param = Newtonsoft.Json.JsonConvert.DeserializeObject<JobExecuteParam>(paramJson);
            if(param != null)
            {
                try
                {
                    if (param.HttpMethod == HttpMethodEnum.POST)
                    {
                        await HttpCllientHelper.PostAsync<Dictionary<string, object>>(param.Params, param.WebhookUrl, param.Timeout, param.Headers).ConfigureAwait(false);
                    }
                    else
                    {
                        await HttpCllientHelper.GetAsync(param.BuildUrlWithParamString(), param.Timeout, param.Headers).ConfigureAwait(false);
                    }
                    Console.WriteLine($"任务 {jobName} 执行成功，时间：{DateTime.Now}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"任务 {jobName} 执行失败，时间：{DateTime.Now}，错误信息：{ex.Message}");
                }
            }
            else
            {
                Console.WriteLine($"任务 {jobName} 执行失败，时间：{DateTime.Now}，错误信息：任务参数解析失败");
            }

        }
    }
}
